package com.awspaas.user.apps.processforsap.event;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.listener.InterruptListener;
import com.actionsoft.bpms.bpmn.engine.listener.InterruptListenerInterface;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.exception.BPMNError;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.cc.RDSAPI;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.sofa.common.profile.StringUtil;
import com.awspaas.user.apps.processforsap.util.HttpClientGwUtil;
import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public class GWTaskValidateForMM extends InterruptListener implements InterruptListenerInterface {
    @Override
    public boolean execute(ProcessExecutionContext ctx) throws Exception {
        /**
         * 电子
         */
        boolean isty = ctx.isChoiceActionMenu("同意");
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (isty) {

            String rdsId = SDK.getRuleAPI().executeAtScript("@getSapParamas(SAP_MID_ID)");
            RDSAPI rdsapi = SDK.getCCAPI().getRDSAPI(rdsId);
            //取值
            BO bo = ctx.getBO("BO_EU_SAP_WLZSJ");

            List<BO> list = SDK.getBOAPI().query("BO_EU_SAP_JBST").bindId(bo.getBindId()).list();


            Set<String> totalS = new HashSet<>();
            for (BO bo1:list){
                String wlmc = bo1.getString("WLMC");
                totalS.add(wlmc);
            }
            if (totalS.size()>1){
                throw new BPMNError("0331","存在不同的物料名称，不允许提交！");
            }


            String matlType2= list.get(0).getString("MATL_TYPE");


            if (!"Z001/Z002/Z005/FERT/HALB".contains(matlType2)){

                //物料特性校验卡控
                BO wltxMainBo = ctx.getBO("BO_EU_SAP_WLTX");
                String watnr = wltxMainBo.getString("MATNR");

                List<BO> listCP = SDK.getBOAPI().query("BO_EU_SAP_CPWLL").bindId(bo.getBindId()).list();
                List<BO> listROH = SDK.getBOAPI().query("BO_EU_SAP_ZCHJCH").bindId(bo.getBindId()).list();
                List<BO> listWAFER = SDK.getBOAPI().query("BO_EU_SAP_WAFER").bindId(bo.getBindId()).list();

                if (watnr.contains("6-GY-00")&&matlType2.equals("Z003"))  {

                }else{
                    if (listROH!=null && listROH.size()>0){
                        BO rohBo = listROH.get(0);
                        String zRohMat = rohBo.getString("Z_ROH_MAT");
                        if (StringUtil.equals("X",zRohMat)){
                            if (StringUtil.isEmpty(rohBo.getString("ZTYPE"))
                                    ||StringUtil.isEmpty(rohBo.getString("ZMATNAME"))
                                    ||StringUtil.isEmpty(rohBo.getString("ZSPEC"))
                                    ||StringUtil.isEmpty(rohBo.getString("ZFIFO"))
                                    ||StringUtil.isEmpty(rohBo.getString("ZNONINSP"))
                                    ||StringUtil.isEmpty(rohBo.getString("ZMATSTATUS"))
                                    ||StringUtil.isEmpty(rohBo.getString("ZCARMATER"))){
                                throw new BPMNError("0331","请在ROH（直材或间材）中补齐型号/物料名称/规格/出库优先级/材料状态/免检/汽车材料字段信息!");
                            }
                            if (watnr.contains("1-MC")){
                                if (StringUtil.isEmpty(rohBo.getString("ZMATNAME"))){
                                    throw new BPMNError("0331","当物料类型为1-MC时，请在ROH（直材或间材）中补齐是否高导热材料字段信息!");
                                }
                            }
                            if (watnr.contains("1-CP")||watnr.contains("1-ID")||watnr.contains("1-RS")){
                                if (StringUtil.isEmpty(rohBo.getString("ZCOMPTYPE"))||StringUtil.isEmpty(rohBo.getString("ZSIZE"))){
                                    throw new BPMNError("0331","当物料类型为1-CP/1-ID/1-RS时，请在ROH（直材或间材）中补齐元器件尺寸/元器件类型字段信息!");
                                }
                            }
                            if (watnr.contains("1-SB")){
                                if (StringUtil.isEmpty(rohBo.getString("ZHAVECU"))
                                        ||StringUtil.isEmpty(rohBo.getString("ZLAYER"))
                                        ||StringUtil.isEmpty(rohBo.getString("ZCORE"))
                                        ||StringUtil.isEmpty(rohBo.getString("ZSUBTYPE"))){
                                    throw new BPMNError("0331","当物料类型为1-SB时，请在ROH（直材或间材）中补齐基板类型/基板层数/基板是否含铜/有无core材字段信息!");
                                }
                            }
                        }
                    }
                }
            }


































            String cs = bo.getString("CS");
            List<BO> tetsList = list.stream().filter(bo1 -> "FERT/HALB".contains(bo1.getString("MATL_TYPE"))).collect(Collectors.toList());
            if (tetsList!=null && tetsList.size()>0){
                if (StringUtil.isEmpty(cs)){
                    throw new BPMNError("0331","产成品或半成品，CS人员必填!");
                }
            }




            String isMc= bo.getString("IS_MC");
            for (BO bo1:list){
                String material = bo1.getString("MATERIAL");
                if ("1".equals(isMc)){
                    if ("1-SB-00-0001623、1-SB-00-0001096、1-SB-00-0000541、1-SB-00-0003089、1-SB-00-0004086、1-SB-00-0002293、1-SB-00-0004838、1-SB-00-0000621、1-SB-00-0003995".contains(material)){

                    }else{
                        throw new BPMNError("0331","您选择了基板，仅能从以下物料号(1-SB-00-0001623、1-SB-00-0001096、1-SB-00-0000541、1-SB-00-0003089、1-SB-00-0004086、1-SB-00-0002293、1-SB-00-0004838、1-SB-00-0000621、1-SB-00-0003995)中选取填写!");
                    }
                }
            }







            String issc = bo.getString("ISSC");
            if ("1".equals(issc)) {

            } else {
                throw new BPMNError("0331", "请点击数据生成生成数据！");
            }
            String cei = bo.getString("CEI");
            for (BO bo1 : list) {
                String status = bo1.getString("STATUS");
                if ("update".equals(status)) {
                    throw new BPMNError("0331", "请点击数据生成生成数据！");
                }
            }
            String cpxh = "";
            //校验重复
            for (BO bo1 : list) {
                String matlType = bo1.getString("MATL_TYPE");
                if ("Z001".equals(matlType) || "Z002".equals(matlType) || "Z005".equals(matlType)) {
                    String plant = bo1.getString("PLANT");
                    String matlGroup = bo1.getString("MATL_GROUP");
                    String basicMatl = bo1.getString("BASIC_MATL");
                    String pageformat = bo1.getString("PAGEFORMAT");
                    //SAP查询
                    String sql = "select * from SAP_MATERIAL_BASIC a,SAP_MATERIAL_PLANT b where a.MATNR = b.MATNR and a.FORMT=? and a.MATKL=? and a.WRKST=?";
                    RowMap result = rdsapi.getMap(sql, pageformat, matlGroup, basicMatl);
                    if (result != null) {
                        throw new BPMNError("0331", "当前在SAP中已存在相同物料组、产品型号、客户三码的数据，请避免重复提交！");
                    } else {
                        String sql1 = "select * from BO_EU_SAP_JBST where PLANT=? and MATL_GROUP = ? and BASIC_MATL=? and PAGEFORMAT = ? AND BINDID !='"+bo.getBindId()+"'";
                        List<RowMap> list1 = DBSql.getMaps(sql1, plant, matlGroup, basicMatl, pageformat);
                        if (list1.size() > 1) {
                            throw new BPMNError("0331", "当前在BPM中已存在相同物料组、产品型号、客户三码的数据，请避免重复提交！");
                        }
                    }
//                    if ("Z002".equals(matlType)){
//                        if (!plant.endsWith("Z")){
//                            throw new BPMNError("0331","当物料类型为Z002时，仅能选择无价厂！");
//                        }
//                    }
                    if ("Z003".equals(matlType) || "ROH".equals(matlType)) {
                        if (plant.endsWith("Z")) {
                            throw new BPMNError("0331", "当物料类型为ROH或Z003时，仅能选择有价厂！");
                        }
                    }

                    //判断产品型号是否相同
                    if (StringUtils.isEmpty(cpxh)) {
                        cpxh = basicMatl;
                    } else {
                        if (!cpxh.equals(basicMatl)) {
                            throw new BPMNError("0331", "基础数据中产品型号不同，不允许提交！");
                        }
                    }
                }
            }

            //存储视图校验
            List<BO> ccList = SDK.getBOAPI().query("BO_EU_SAP_CCST").bindId(bo.getBindId()).list();
            Object validitydate = SDK.getProcessAPI().getVariable(bo.getBindId(), "VALIDITYDATE");
            if (validitydate != null) {
                String resultData = String.valueOf(validitydate);
                if ("false".equals(resultData)) {
                    for (BO bo1 : ccList) {
                        int shelfLife = Integer.valueOf(StringUtil.isEmpty(bo1.getString("SHELF_LIFE")) ? "0" : bo1.getString("SHELF_LIFE"));
                        if (shelfLife <= 0) {
                            throw new BPMNError("0331", "存储视图总货架寿命必填，请核查！");
                        }
                    }
                }else{
                    for (BO bo111 : ccList) {
                        int shelfLife = Integer.valueOf(StringUtil.isEmpty(bo111.getString("SHELF_LIFE")) ? "0" : bo111.getString("SHELF_LIFE"));
                        if (shelfLife <= 0) {
                            throw new BPMNError("0331", "存储视图总货架寿命必填，请核查！");
                        }
                    }
                }
            }

            for (BO bo222 : list) {
                String matlType1 = bo222.getString("MATL_TYPE");
                if (matlType1.equals("Z001") || matlType1.equals("Z005") || matlType1.equals("Z002")) {
                    if (StringUtils.isEmpty(cei)) {
                        throw new BPMNError("0331", "当物料类型为Z001或Z002或Z005时，CEI人员必填");
                    }
                }
            }


            BO boJbst = list.get(0);
            String matlType = boJbst.getString("MATL_TYPE");
            String matlGroup = boJbst.getString("MATL_GROUP");


            String isBg = bo.getString("IS_BG");
            //获取物料特性
            BO bo1 = SDK.getBOAPI().query("BO_EU_SAP_CPWLL").detailByBindId(bo.getBindId());
            if ("FERT".equals(matlType) || "HALB".equals(matlType)) {
                if (bo1 == null) {
                    throw new BPMNError("0331", "当物料类型为FERT或HALB时，物料特性表必填");
                }
                String zassemtype = bo1.getString("ZASSEMTYPE");
                if (StringUtil.isEmpty(zassemtype)) {
                    throw new BPMNError("0331", "当物料类型为FERT或HALB时，物料特性表中封测类型必填");
                }
            }


            BO bo2 = SDK.getBOAPI().query("BO_EU_SAP_ZCHJCH").detailByBindId(bo.getBindId());
            BO bo3 = SDK.getBOAPI().query("BO_EU_SAP_WAFER").detailByBindId(bo.getBindId());
            String specifiCations = "";
            String zgyunit = "";
            String copGName = "";
            if (bo1 != null) {
                if (StringUtil.isNotEmpty(bo1.getString("ZSPEC"))) {
                    specifiCations = bo1.getString("ZSPEC");
                }
                if (StringUtil.isNotEmpty(bo1.getString("ZGYUNIT"))) {
                    zgyunit = bo1.getString("ZGYUNIT");
                }
                if (StringUtil.isNotEmpty(bo1.getString("ZMATNAME"))) {
                    copGName = bo1.getString("ZMATNAME");
                }
            }
            if (bo2 != null) {

                String zcmatnr = bo2.getString("ZCMATNR");
                String zcustomcode = bo2.getString("ZCUSTOMER");
                String zsize = bo2.getString("ZSIZE");
                String zcomptype = bo2.getString("ZCOMPTYPE");
                String zgg = bo2.getString("ZGG");
                String zcarmater = bo2.getString("ZCARMATER");


                if (StringUtil.isNotEmpty(bo2.getString("ZSPEC"))) {
                    specifiCations = bo2.getString("ZSPEC");
                }
                if (StringUtil.isNotEmpty(bo2.getString("ZGYUNIT"))) {
                    zgyunit = bo2.getString("ZGYUNIT");
                }
                if (StringUtil.isNotEmpty(bo2.getString("ZMATNAME"))) {
                    copGName = bo2.getString("ZMATNAME");
                }
            }

            if ("1".equals(isBg)) {
                if (StringUtil.isEmpty(zgyunit)) {
                    throw new BPMNError("0331", "当是否报关选择是是，物料特性表中海关物料单位必填");
                }
            }

            //公司代码
            //获取币种
            String currency = bo.getString("CURRENCY");

            for (BO bo222 : list) {
                String matlType1 = bo222.getString("MATL_TYPE");
                String matlGroup1 = bo222.getString("MATL_GROUP");
                if (currency.equals("CNY")) {
                    if (matlType1.equals("HALB") || matlType1.equals("FERT")) {

                    } else if (!matlType1.equals("Z002")) {
                        throw new BPMNError("0331", "人民币客户，只能选择Z002物料类型");
                    }
                }
                if (currency.equals("USD")) {
                    if (matlType1.equals("HALB") || matlType1.equals("FERT")) {

                    }else{
                        if (matlGroup1.startsWith("1-WF") || matlGroup1.startsWith("1-IC-00")) {
                            if (!matlType1.equals("Z001") && !matlType1.equals("Z005")) {
                                throw new BPMNError("0331", "美金客户：1-WF/1-IC-00 只允许创建Z001&Z005属性物料");
                            }
                        } else {
                            if (!matlType1.equals("Z002")) {
                                throw new BPMNError("0331", "美金客户：非1-WF/1-IC-00物料组只允许创建Z002属性物料");
                            }
                        }
                    }

                }
            }




        }
        return true;
    }
}
